<template>
  <!-- 工作年限薪酬分布 -->
  <div>
    <!-- <span class="tinyTitle">
      <div class="titleFlag"></div>
      {{ "工作经验薪酬详情" }}
    </span> -->
    <el-row class="search-container">
      <el-form ref="form" label-width="auto">
        <el-form-item label="统计时间：">
          <el-date-picker
            v-model="selectBetweenTime"
            :clearable="false"
            size="small"
            type="monthrange"
            align="right"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            :picker-options="pickerOptions"
            @change="handleDateChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="区域名称：">
          <multipleRegoinSearch
            :limit-num="1"
            ref="regionRef"
            @onRegionChange="onRegionChange"
          />
        </el-form-item>
      </el-form>
    </el-row>
    <div class="chartMain">
      <template v-if="chartDataIsNotEmpty">
        <div class="h100" ref="line_echartDom"></div>
        <div class="regionLineDesc">
          <div class="cityTitle">{{ currentChartRegionName }}</div>
          <div
            class="regionLineDescItem"
            v-for="(item, index) in chartDescData"
            :key="index"
          >
            <div class="descTitle">{{ item.expCodeStr }}平均薪酬约</div>
            <div class="descNum">
              <span class="rmb">￥</span>{{ item.salaryNum }}/<span class="rmb"
                >月</span
              >
            </div>
          </div>
        </div>
      </template>
      <el-empty class="empty" description="暂无数据" v-else
        ><el-button type="primary" size="mini" @click="handleKnowClick()">
          想要了解
        </el-button></el-empty
      >
    </div>
  </div>
</template>

<script>
import { getSalaryWorkYear, reportLackDataPosition } from '@/api/salary';
import multipleRegoinSearch from '@/views/position/components/multipleRegoinSearch.vue';
export default {
  name: 'workBarChart',
  components: {
    multipleRegoinSearch
  },
  data() {
    return {
      resData: [],
      chartDataIsNotEmpty: true, //必须让图表先显示，不然会出现空白
      chartData: {},
      selectBetweenTime: [],
      pickerMinDate: '',
      firstDayofLastMonth: '',
      pickerOptions: {
        showClear: false,
        disabledDate: (time) => {
          const nowTime = time.getTime();
          if (nowTime < 1672502400000 || nowTime > this.firstDayofLastMonth) {
            return true;
          }
          if (this.pickerMinDate) {
            const monthsDiff =
              Math.abs(nowTime - this.pickerMinDate) /
              (1000 * 60 * 60 * 24 * 30);
            // 如果相差的月份大于6个月，则禁用该日期
            return monthsDiff > 6 || nowTime < 1672502400000;
          }
        },
        onPick: (obj) => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        }
      },
      average: '',
      selectedRegionList: [],
      regionLineDescAvg: '',
      isSetDeaultTime: false,
      isSetDeaultRegion: true,
      currentChartRegionName: '全国',
      chartDescData: []
    };
  },
  computed: {
    isLabelShow() {
      return this.$store.state.chart.isLabelShow;
    }
  },
  created() {
    // 创建一个表示当前日期的 Date 对象
    var currentDate = new Date();

    // 将当前日期设置为本月的第一天
    currentDate.setDate(1);

    // 将当前日期减去一天，得到上个月最后一天
    currentDate.setDate(0);

    // 设置时间为零点
    currentDate.setHours(0, 0, 0, 0);

    // 获取时间戳
    var timestamp = currentDate.getTime();

    this.firstDayofLastMonth = timestamp;
  },
  mounted() {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let newYear = 0;
    let newMonth = 0;
    let newDateArr = [];
    for (let i = 0; i < 7; i++) {
      //这里是获取前六个月,所以循环6次,根据需要修改
      if (month - i < 1) {
        //这里的判断是如果当前月份往前推到了去年  需要做的处理
        newYear = year - 1;
        newMonth =
          month - i + 12 >= 10 ? month - i + 12 : '0' + (month - i + 12);
        newDateArr.push(newYear + '-' + newMonth + '-' + '01'); //这里拼接格式化,在时间中间加了个-,根据实际需求来
      } else {
        newMonth = month - i >= 10 ? month - i : '0' + (month - i); //这里是对月份小于10做加前面加0处理
        newDateArr.push(year + '-' + newMonth + '-' + '01');
      }
    }
    //这里就最后得到当前年月前六个月组成的时间数组,根据需要赋值使用即可
    const end = newDateArr[1];
    const start = newDateArr[6];
    this.selectBetweenTime = [start, end];
    this.fetchData();
  },
  methods: {
    getWorkYearClass(index) {
      const obj = {
        0: 'pink',
        1: 'green',
        2: 'blue',
        3: 'skyBlue',
        4: 'brown'
      };
      return obj[index];
    },
    fetchData() {
      this.listLoading = true;
      const params = {
        id: this.$route.query.id
      };
      // params.beginTime = "2023-1-1";
      // params.endTime = "2023-5-1";
      if (this.selectBetweenTime) {
        params.beginTime = this.selectBetweenTime[0];
        params.endTime = this.selectBetweenTime[1];
        // params.beginTime = "2023-1-1";
        // params.endTime = "2023-5-1";
      }
      params.regionIds = this.selectedRegionList.join('_');
      getSalaryWorkYear(params)
        .then((response) => {
          if (response.code == 200) {
            // //console.log("getSalaryWorkYear---------->",response);
            this.resData = response.data;
            this.chartDescData = response.data;
            this.chartData = this.handleData(response.data);
            this.chartDataIsNotEmpty =
              response.data && response.data.length > 0;
            setTimeout(() => {
              this.init();
            }, 500);
          } else {
            this.chartDataIsNotEmpty = false;
          }
        })
        .catch(() => {
          this.chartDataIsNotEmpty = false;
        });
    },
    handleData(data) {
      // 降序
      // //console.log("handleData", data);

      // data.sort((a, b) => {
      //   return b.salaryNum - a.salaryNum;
      // });
      let dataArr = {
        city: [],
        salary: []
      };
      data.forEach((element) => {
        dataArr.city.push(element.expCodeStr);
        dataArr.salary.push(element.salaryNum);
      });

      return dataArr;
    },
    init() {
      if (!this.$refs['line_echartDom']) return;
      this.myChart = this.$echarts.init(this.$refs['line_echartDom']);
      let city = this.chartData.city,
        salary = this.chartData.salary;
      let option = {
        xAxis: {
          type: 'category',
          data: city,
          name: '(工作年限)',
          interval: 0,
          // boundaryGap: false,
          axisLabel: {
            // formatter(val) {
            //   // 当字符串长度超过2时
            //   if (val.length > 2) {
            //     // 把字符串分割成字符串数组
            //     const array = val.split("");
            //     const index = array.indexOf("市");
            //     //在下标2处删除0个，加上回车
            //     array.splice(index, 1);
            //     return array.join("");
            //   } else {
            //     return val;
            //   }
            // },
            color: '#8193B2'
            // fontSize: "13px",
          },
          axisLine: {
            lineStyle: {
              color: '#E4EDF8'
            }
          },
          nameTextStyle: {
            lineHeight: 30, //标题行高
            color: '#8193B2',
            verticalAlign: 'top', //标题位置
            padding: [-2, 0, 0, 0] // 上右下左与原位置距离
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: '#000000'
            }
          },
          backgroundColor: '#FB9A3E',
          borderColor: '#FB9A3E',
          textStyle: {
            color: '#fff'
          },
          formatter: (params) => {
            const content = params[0];
            return `月收入平均值 ¥${content.value}`;
          }
          // position: ["50%", 0],
        },
        grid: {
          top: '50',
          left: '50',
          right: '80',
          // right: "4%",
          bottom: '50'
          // containLabel: true,
        },
        yAxis: {
          type: 'value',
          // scale: true,
          name: '(薪酬 元)',
          axisLabel: {
            color: '#8193B2',
            fontSize: '12px'
          },
          axisLine: {
            lineStyle: {
              color: '#E4EDF8'
            }
          },
          nameTextStyle: {
            padding: [0, 45, 10, 0], // 上右下左与原位置距离

            color: '#8193B2'
          }
        },
        series: [
          {
            data: salary,
            type: 'bar',
            showBackground: false,
            barWidth: '18px',
            label: {
              show: this.isLabelShow,
              position: 'top'
            },
            itemStyle: {
              normal: {
                color: this.$echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  {
                    //只要修改前四个参数就ok
                    offset: 0,
                    color: '#FFC48C'
                  }, //柱图渐变色
                  {
                    offset: 1,
                    color: '#BCF3C6'
                  }
                ]),
                borderRadius: [4, 4, 0, 0]
              }
            },
            emphasis: {
              itemStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: '#FF9735' // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: '#77D98A' // 100% 处的颜色
                    }
                  ],
                  global: false // 缺省为 false
                }
              }
            }
          }
        ]
      };
      this.myChart.on('mouseover', (params) => {
        this.$emit('update:hoverValue', params.value);
        this.$emit('update:hoverName', params.name);
      });
      option && this.myChart.setOption(option);
      window.addEventListener('resize', () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      document.addEventListener('fullscreenchange', function () {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      this.myChart.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: 1
      });
      this.$emit('update:hoverValue', this.chartData.salary[1]);
      this.$emit('update:hoverName', this.chartData.city[1]);
    },
    // init() {
    //   this.myChart = this.$echarts.init(this.$refs["line_echartDom"]);
    //   let city = this.chartData.city,
    //     name = this.chartData.name,
    //     time = this.chartData.time;
    //   let option = {
    //     color: [
    //       "#F359AE",
    //       "#34CA6F",
    //       "#066BFF",
    //       "#75E0FF",
    //       "#FFA506",
    //       "#3ba272",
    //       "#fc8452",
    //       "#9a60b4",
    //       "#ea7ccc",
    //     ],
    //     xAxis: {
    //       type: "category",
    //       data: time,
    //       name: "（时间）",
    //       // boundaryGap: false,
    //       axisLabel: {
    //         formatter(val) {
    //           // 当字符串长度超过2时
    //           if (val.length > 2) {
    //             // 把字符串分割成字符串数组
    //             const array = val.split("");
    //             const index = array.indexOf("月");
    //             //在下标2处删除0个，加上回车
    //             array.splice(index + 1, 0, "\n");
    //             return array.join("");
    //           } else {
    //             return val;
    //           }
    //         },
    //         color: "#8193B2",
    //         fontSize: "12px",
    //       },
    //       axisLine: {
    //         lineStyle: {
    //           color: "#E4EDF8",
    //         },
    //       },
    //       nameTextStyle: {
    //         lineHeight: 30, //标题行高
    //         color: "#8193B2",
    //         verticalAlign: "top", //标题位置
    //       },
    //     },
    //     tooltip: {
    //       trigger: "axis",
    //     },
    //     legend: {
    //       data: name,
    //       orient: "vertical",
    //       align: "left",
    //       colorBy: "",
    //       x: "right", //可设定图例在左、右、居中
    //       y: "center", //可设定图例在上、下、居中
    //       icon: "circle",
    //       itemGap: 24,
    //       itemWidth: 10,
    //       itemHeight: 10,
    //       textStyle: {
    //         fontSize: "14px",
    //       },
    //       padding: [0, 0, 0, 100],
    //     },
    //     grid: {
    //       // left: "20%",
    //       // right: "4%",
    //       // bottom: "3%",
    //       left: time.length ? "0" : "10%",
    //       containLabel: true,
    //     },
    //     yAxis: {
    //       type: "value",
    //       // scale: true,
    //       name: "（薪酬）",
    //       min: function (value) {
    //         return value.min - 20;
    //       },
    //       axisLabel: {
    //         color: "#8193B2",
    //         fontSize: "12px",
    //       },
    //       nameTextStyle: {
    //         color: "#8193B2",
    //         padding: [0, 45, 0, 0], // 上右下左与原位置距离
    //       },
    //     },
    //     series: [],
    //   };
    //   option.series = [];
    //   this.myChart.clear();
    //   city.forEach((item) => {
    //     option.series.push({
    //       data: item.salary,
    //       name: item.name,
    //       type: "line",
    //       smooth: true,
    //       symbolSize: 10,
    //       symbol: "path://M349 889.5a7.5 7.5 0 1 0 15 0a7.5 7.5 0 1 0 -15 0z",
    //       showSymbol: false,
    //       label: {
    //         normal: {
    //           show: false,
    //         },
    //       },
    //       emphasis: {
    //         label: {
    //           // show: true,
    //         },
    //       },
    //     });
    //   });
    //   option && this.myChart.setOption(option);
    //   window.addEventListener("resize", () => {
    //     if (this.myChart) {
    //       this.myChart.resize();
    //     }
    //   });
    //   this.myChart.dispatchAction({
    //     type: "showTip",
    //     seriesIndex: 0,
    //     dataIndex: 1,
    //   });
    // },
    onWorkYearChange(val) {
      this.fetchData();
    },
    handleDateChange(val) {
      if (this.isSetDeaultTime) {
        this.isSetDeaultTime = false;
        return;
      }
      this.pickerMinDate = null;
      this.fetchData();
    },
    onRegionChange(val) {
      // //console.log("workLineChart------onRegionChange----------->",val);
      this.currentChartRegionName = val[0].split('-')[1];
      this.selectedRegionList = [];
      val.forEach((item) => {
        this.selectedRegionList.push(item.split('-')[0]);
      });
      if (this.isSetDeaultRegion) {
        this.isSetDeaultRegion = false;
        return;
      }
      this.fetchData();
    },
    handleKnowClick() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo')); //OA的userInfo和SaaS登录的userInfo不一样
      const oaId = '';
      if (userInfo && userInfo.user_source_id) {
        oaId = userInfo.user_source_id;
      }
      const params = {
        positionId: this.$route.query.id,
        positionName: this.$route.query.name,
        layerId: '44',
        layerName: '工作年限薪酬分布',
        personId: localStorage.getItem('personId') || '',
        oaId: oaId
      };
      reportLackDataPosition(params).then((response) => {
        if (response.code == 200) {
          this.$message.success('已成功提交');
        } else {
          this.$message.error(res.status_desc);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.pink {
  font-weight: bold;
}
.green {
  font-weight: bold;
}
.blue {
  font-weight: bold;
}
.skyBlue {
  font-weight: bold;
}
.brown {
  font-weight: bold;
}
.tinyTitle {
  display: flex;
  align-items: center;
  font-size: 18px;
  margin-top: 16px;
  color: #222;
  font-weight: bold;
  margin-bottom: 22px;
  .titleFlag {
    width: 5px;
    height: 15px;
    border-radius: 3px;
    background: #4880ff;
    margin-right: 12px;
  }
}
.chartMain {
  display: flex;
  .empty {
    margin: auto;
    ::v-deep .el-empty__image {
      width: 150px;
    }
  }
  // align-items: center;
  .h100 {
    flex: 0.65;
  }
  .regionLineDesc {
    /* // margin-left: 45px; */
    display: flex;
    flex: 0.35;
    flex-wrap: wrap;
    /* width: 400px; */
    justify-content: space-between;
    // align-content: center;
    margin: 10px 10px 10px 10px;
    .cityTitle {
      display: flex;
      width: 100%;
      margin: 10px auto;
      font-size: 18px;
      font-weight: bold;
      color: #222;
      align-items: center;
    }
    .cityTitle::before {
      content: '';
      display: inline-block;
      width: 8px;
      height: 8px;
      top: 50%;
      border-radius: 50%;
      background-color: #fb9a3e;
      margin-right: 8px;
    }
    .regionLineDescItem {
      margin: 10px 0px;
      width: 48%;
    }
    .descTitle {
      color: #555;
      font-size: 15px;
    }
    .descNum {
      display: flex;
      align-items: baseline;
      color: #1b78ff;
      font-size: 24px;
      font-weight: bold;
      margin-top: 22px;
      font-family: D-DIN-PRO-500-Medium;
    }
    .rmb {
      font-size: 18px;
    }
  }
}
.regionLineChart {
  display: flex;
  align-items: center;
}
.regionLineDesc {
  margin-left: 5vw;
  .regionLineDescItem {
    margin-top: 25px;
  }
  .regionLineDescItem:first-of-type {
    margin-top: 0;
  }
}
.descTitle {
  color: #555;
  font-size: 16px;
  span {
  }
}
.descNum {
  display: flex;
  align-items: baseline;
  color: #1b78ff;
  font-size: 20px;
  font-weight: bold;
  margin-top: 22px;
  font-family: D-DIN-PRO-600-SemiBold;
}

.rmb {
  font-size: 18px;
}
.h100 {
  width: 100%;
  // height: 20vw;
  min-width: 615px;
  min-height: 280px;
}
::v-deep .el-date-editor {
  background: #fafcfe;
  border-radius: 4px;
  border: 1px solid #e4edf8;
}
::v-deep .el-form-item:last-of-type {
  margin-bottom: 0px;
}
::v-deep .el-form-item__label {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #555555;
  line-height: 22px;
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 内容超出容器部分隐藏 */
  text-overflow: ellipsis; /* 使用省略号表示被截断的内容 */
}
::v-deep .el-form-item {
  margin-bottom: 6px;
}
::v-deep .el-form-item__label-wrap {
  margin-left: 0px !important;
}
.search-container {
  display: flex;
  align-items: center;
}
</style>
